<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div>
        <el-button type="primary" size="mini" @click="addCategory"
          >添加</el-button
        >
      </div>

      <tree-table
        class="tree-table"
        :data="
          categoryList.slice(
            (queryInfo.pagenum - 1) * queryInfo.pagesize,
            queryInfo.pagenum * queryInfo.pagesize
          )
        "
        :columns="columns"
        show-index
        border
        :expand-type="false"
        :selection-type="false"
        :show-row-hover="true"
      >
        <!-- 是否有效 -->
        <template slot="isok" scope="scope">
          <i v-if="scope.row.cat_deleted" class="el-icon-success" style=""></i>
          <i v-else class="el-icon-error"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" scope="scope">
          <el-tag type="info" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="info" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="info" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="operation" scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="editCategory(scope.row.cat_id)"
            ><i class="el-icon-edit">编辑</i></el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="deleteCategory(scope.row.cat_id)"
            ><i class="el-icon-delete">删除</i></el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.querypagenum"
        :page-sizes="[5, 10, 20]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加商品分类对话框 -->
      <el-dialog title="添加商品分类" :visible.sync="addCategoryDialogVisible">
        <!-- 内容区域 -->
        <el-form
          ref="addCategoryFormRef"
          :model="addCategoform"
          label-width="80px"
          :rules="addCategoryRules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCategoform.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectedCascader"
              :options="categoryFathers"
              :props="casterprops"
              @change="parentCateChanged"
              :clearable="true"
              :change-on-select="true"
            ></el-cascader>
          </el-form-item>
        </el-form>

        <!-- 操作区域 -->
        <div slot="footer">
          <el-button @click="cancelAddCategoryDialog">取 消</el-button>
          <el-button type="primary" @click="addCategoryConfirm"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- 修改商品分类 -->
      <el-dialog title="修改商品分类" :visible.sync="editCategoryDialogVisible">
        <el-form
          ref="editCategoryFormRef"
          :model="addCategoform"
          label-width="80px"
          :rules="addCategoryRules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCategoform.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectedCascader"
              :options="categoryFathers"
              :props="casterprops"
              @change="parentCateChanged"
              :clearable="true"
              :change-on-select="true"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editCategoryCancel">取 消</el-button>
          <el-button type="primary" @click="editCategoryConfirm()"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
data(){
        return {
         categoryList:[],
            // 分页
            total:0,
          queryInfo:{
            type:1,
            pagenum:1,//当前页码
            pagesize:5,//显示数量
          },
        //   表格的列
          columns:[{
            label: '商品类别名称',
            prop: 'cat_name',
            width: '400px',
          },
           {
            label: '是否可以使用',
            type: 'template',
            template: 'isok',
            align:'center'
          },
           {
            label: '排序',
            type: 'template',
            template: 'order',
            align:'center'
          },
          {
            label: '操作',
            type: 'template',
            template: 'operation',
            width:'180px',
            align:'center',
          },
          ],

        //   添加商品分类对话框
        addCategoryDialogVisible:false,//控制对话框隐藏和显示
        addCategoform:{
            cat_name:'',
            cat_pid:0,
            cat_level:0
        },

        addCategoryRules:{
           cat_name: [
               { required: true, message: '请输入活动名称', trigger: 'blur' },
           ]
        },
        categoryFathers:[],//父类分类列表
        // 设置级联下拉框和categoryFather对应
        casterprops:{
            label:'cat_name',
            value:'cat_id',
            children:'children'
        },
        selectedCascader:[],
        //修改商品分类对话框
        editCategoryDialogVisible : false,
        currentID:''



        }
    },
    methods: {
      async getGoodsCategory(){
          const {data:res} =  await this.$http.get('/categories')
          if(res.meta.status!==200){return this.$message.error('商品分类信息获取失败');}
          this.categoryList = res.data
          this.total = this.categoryList.length

        },
        // 分页函数
        handleCurrentChange(val){
            this.queryInfo.pagenum=val
        },
        handleSizeChange(val){
            this.queryInfo.pagesize= val
           
        },
        // 添加商品分类
        addCategory(){
            this.getCategotyFather()
            this.addCategoryDialogVisible=true
        },
        // 获取前两级分类
      async  getCategotyFather(){
          const {data:res} = await this.$http.get('categories',{params:{type:2}})
          if(res.meta.status!==200) {return this.$message.error('获取不到父类分类信息')}
          this.categoryFathers = res.data
        },
// 级联选择框选中之后的操作
        parentCateChanged(){
            if(this.selectedCascader.length===0){
               this.addCategoform.cat_level=0
               this.addCategoform.cat_pid=0
            }else{
            let len = this.selectedCascader.length
            this.addCategoform.cat_pid = this.selectedCascader[len-1]
            this.addCategoform.cat_level = len
            }
        },
        cancelAddCategoryDialog(){
            this.$refs.addCategoryFormRef.resetFields()
            this.selectedCascader=[]
            this.addCategoform.cat_pid=0
            this.addCategoform.cat_level=0
            this.addCategoryDialogVisible=false
        },
  

        // 确认添加分类
       async addCategoryConfirm(){
         const {data:res}  = await  this.$http.post('categories',this.addCategoform)
        if(res.meta.status!==201){
            return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.selectedCascader=[]
            this.addCategoform.cat_pid=0
            this.addCategoform.cat_level=0
        this.$refs.addCategoryFormRef.resetFields()
        this.addCategoryDialogVisible = false
        this.getGoodsCategory()
        },

        // 编辑   操作
   // 根据当前选中的id，获取所有祖父id
       async getPidByid(pidList,cid){
         const{data:res} = await this.$http.get('categories/'+cid)
          if(res.meta.status!==200){
               return this.$message.error('根据id获取分类信息失败')
           }
           if(res.data.cat_level===1){
               pidList.unshift(res.data.cat_pid)
            //    console.log('第二次push',pidList,pidList.length)
           }else if(res.data.cat_level===2){
                 pidList.unshift(res.data.cat_pid)
                //  console.log('第一次push',pidList,pidList.length)
              await this.getPidByid(pidList,res.data.cat_pid)
           }            
        },
        // 修改分类操作
        async editCategory(cid){
            this.getCategotyFather()
           const{data:res} = await this.$http.get('categories/'+cid)
           if(res.meta.status!==200){
               return this.$message.error('根据id获取分类信息失败')
           }
           this.currentID = res.data.cat_id
           this.addCategoform.cat_name = res.data.cat_name
           this.addCategoform.cat_level=res.data.cat_level
           this.addCategoform.cat_pid = res.data.cat_pid
        //    console.log(this.addCategoform)
           let pidList=[]
           this.selectedCascader =[]
           await this.getPidByid(pidList,res.data.cat_id)
        //    console.log('调用完this.getPidByid函数后',pidList,pidList.length)

          this.selectedCascader = pidList.concat()

        //    console.log('this.selectedCascader:',this.selectedCascader)
     
      
            // 获取数据展示到对话框

            this.editCategoryDialogVisible = true

        },
        editCategoryCancel(){
            this.$refs.editCategoryFormRef.resetFields()
            this.selectedCascader=[]
            this.addCategoform.cat_pid=0
            this.addCategoform.cat_level=0
            this.currentID = 0
            this.editCategoryDialogVisible = false
        },
        async editCategoryConfirm(){
           const{data:res} = await this.$http.put('categories/'+this.currentID,{'cat_name':this.addCategoform.cat_name})
           if(res.meta.status!==200){
               return this.$message.error('修改分类信息提交失败')
           }
           this.$message.success('修改分类信息提交成功')
           this.getGoodsCategory()
           this.editCategoryCancel()

        },



        
        // 删除分类操作
       async deleteCategory(cid){
           console.log(cid)
           const {data:res} = await this.$http.delete('categories/'+cid)
           if(res.meta.status!==200){
               return this.$message.error('删除失败')
           }
           this.$message.success('删除成功')
           this.getGoodsCategory()


        }




    },
    created() {
        this.getGoodsCategory()
    },
}
</script>

<style scoped>
.tree-table {
  margin-top: 20px;
}
</style>